var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require("fs");
var session = require('express-session');


//自定义文件引入
var index = require('./routes/index');
var users = require('./routes/admin/users');
var db = require('./utils/db');
var personalTask = require('./routes/personalTask/personalTask');
var login = require('./routes/login');
var project = require('./routes/admin/project');
var feedBack = require('./routes/process/feedBack');
var person = require('./routes/admin/person');
var modules = require('./routes/module/module');
var operationFile = require('./routes/admin/operationFile');
var processModule = require('./routes/process/module');
var processRequirement = require('./routes/process/requirement');
var processHistoryVersion = require('./routes/process/historyVersion');
var processActivity = require('./routes/process/activity');
var processDesign = require('./routes/process/design');
var processIteration = require('./routes/process/iteration');
var dailyDayReport = require('./routes/daily/dayReport');
var dailyWeekPlan = require('./routes/daily/weekPlan');
var dailyWeek = require('./routes/daily/week');
var dailyDay = require('./routes/daily/day');
var dailyWord = require('./routes/daily/word');
var dailyWordType = require('./routes/daily/wordType');
var schedule = require('./routes/daily/schedule');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views_ejs'));
app.set('view engine', 'ejs');
app.locals.moment = require('moment');
app.locals.dateFormat = 'YYYY-MM-DD HH:mm:ss';
app.locals.shortDateFormat = 'YYYY-MM-DD';

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//session 会话
app.use(cookieParser('sessiontest'));
app.use(session({
    secret: 'sessiontest',//与cookieParser中的一致
    resave: true,
    saveUninitialized: true
}));
app.use(function (req, res, next) {
    res.locals.session = req.session;
    next();
});
//登录拦截器
app.use(function (req, res, next) {
    if (req.session.loginedUser) {
        next();
    } else {
        var url = req.originalUrl;
        if (url === "/login" || url === '/loginHandler') {
            next();
        } else {
            res.redirect("/login");
            res.end();
        }
    }
});

//路由映射
app.use('/', index);
app.use('/', login);
app.use('/users', users);
app.use('/project', project);
app.use('/process/feedBack', feedBack);
app.use('/person', person);
app.use('/personalTask', personalTask);
app.use('/module', modules);
app.use('/operationFile', operationFile);
app.use('/process/module', processModule);
app.use('/process/requirement', processRequirement);
app.use('/process/historyVersion', processHistoryVersion);
app.use('/process/activity', processActivity);
app.use('/process/design', processDesign);
app.use('/process/iteration', processIteration);
app.use('/daily/week', dailyWeek);
app.use('/daily/weekPlan', dailyWeekPlan);
app.use('/daily/dayReport', dailyDayReport);
app.use('/daily/day', dailyDay);
app.use('/daily/word', dailyWord);
app.use('/daily/wordType', dailyWordType);
app.use('/daily/schedule', schedule);



// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development

    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});


//初始化sql
console.log('数据库初始化开始');
fs.readFile('./sql/create.sql', 'utf8', function (err, data) {
    db.query(data, function (err, rows) {
        if (err) {
            console.log('数据库初始化失败');
        } else {
            console.log('数据库初始化完成');
        }
    });
});

module.exports = app;
